import { Component, Input, OnInit, ViewChild, ElementRef} from '@angular/core';
import { AlertController, PopoverController } from '@ionic/angular';
import { ModalController } from '@ionic/angular';
import { AppGlobalService } from 'src/app/shared/service/app-global.service';
import { EventService } from 'src/app/shared/service/event.service';
import { HttpService } from '../../shared/service/http.service';

declare var cordova: any;
declare var BMap;
declare var BMAP_ANCHOR_BOTTOM_RIGHT;

@Component({
    selector: 'app-logistics-trajectory',
    templateUrl: './logistics-trajectory.component.html',
    styleUrls: ['./logistics-trajectory.component.scss']
})
export class LogisticsTrajectoryComponent implements OnInit {
    constructor(
        private httpService: HttpService,
        public appGlobalService: AppGlobalService,
        public alertController: AlertController,
        public modalController: ModalController,
        public eventService: EventService,
        public popoverController: PopoverController
    ) {}
    @Input() tagData: any;
    @ViewChild('addressMap') mapElement: ElementRef;

    private myGeo = { lng: 113.931058, lat: 22.517712 };
    map: any;

    ngOnInit() {
        setTimeout(() => {
            if (this.tagData.data && this.tagData.data.data && this.tagData.data.data.length > 0) {
                this.initMap(this.myGeo);
            }
        }, 0);
    }

    copyClick(e, str, msg?) {
        msg?msg:msg = '单号';
        this.appGlobalService.copyStr(e, str, msg);
    }

    async call(mobile, name) {
        const alert = await this.alertController.create({
            header: this.tagData.data.nick_name,
            message: name + " " + mobile,
            buttons: [
                {
                    text: '取消',
                    role: 'cancel',
                    cssClass: 'secondary'
                }, {
                    text: '拨打',
                    handler: () => {
                        this.httpService.changeCallNumber(mobile);
                    }
                }
            ]
        });
        await alert.present();
    }

    selectPhoneNumber(str) {
        const mobile = /(1[0-9]{10})|([0-9]{3,4})?[0-9]{7,8}/g; // 匹配手机号或固话
        let num = str.replace(/\s|[(]|[)]|[（]|[）]|[-]*/g, ''); // 去除字符串中所有空格、小括号和横杠
        const phone = num.match(mobile); // 识别手机号或者固话
        if (phone && phone.length > 0) {
            const newArr = phone.filter((item, index) => {
                return phone.indexOf(item) === index;  // 因为indexOf 只能查找到第一个
            });

            // tslint:disable-next-line:prefer-for-of
            for (let i = 0; i < newArr.length; i++) {
                const temp = newArr[i];
                num = num.replace(newArr[i], '<a href="tel:'
                    + temp
                    + '"  class="copy phone-num" style=" text-decoration: underline;color: #2878FF;">'
                    + temp
                    + '</a>');
            }
        }

        return num;
    }

    initMap(pt) {
        const that = this;
        const map = that.map = new BMap.Map(that.mapElement.nativeElement, { minZoom: 5, maxZoom: 8, enableMapClick: true });

        map.disableKeyboard();
        map.disableDoubleClickZoom();
        map.disableScrollWheelZoom();
        map.disableContinuousZoom();
        let points: any = [];
        let pointData = JSON.parse(JSON.stringify(that.tagData.data.data));
        pointData.reverse().forEach(e => {
            const [pointX, pointY] = e.areaCenter.split(',');
            points.push(new BMap.Point(pointX, pointY));
        });

        // 起点
        const cust = new BMap.Icon("/assets/img/map/map_icon_location_red@3x.png", new BMap.Size(24, 34));
        let point = points[0];
        let marker = new BMap.Marker(point, { icon: cust });
        map.addOverlay(marker);

        // 终点（当前点）
        if (points.length > 1) {
            const gps = new BMap.Icon("/assets/img/map/map_icon_location@3x.png", new BMap.Size(25, 25));
            let gpsPoint = points[points.length - 1];
            let gpsMarker = new BMap.Marker(gpsPoint, { icon: gps });
            map.addOverlay(gpsMarker);
        }

        // push points
        // 创建轨迹
        let polyline = new BMap.Polyline(points, {strokeColor:"#f86a25", strokeWeight:2});
        
        // 将轨迹添加到地图
        map.addOverlay(polyline);
        
        // 自适应设置缩放级别和中心点
        const viewport = map.getViewport(points);
        // 平移至轨迹的可视范围
        map.setViewport(viewport);

        // 隐藏百度的logo
        map.addEventListener("tilesloaded", () => {
            const objs = document.getElementsByClassName("anchorBL");
            if (objs !== undefined && objs.length > 0) {
                for (let i = 0, len = objs.length; i < len; i++) {
                    if (objs[i] !== undefined) {
                        objs[i].setAttribute("style", "display:none;");
                    }
                }
            }
        });
    }


    // getExpressDemoData() {

    //     return {
    //         message: "ok",
    //         nu: "78716310792032",
    //         ischeck: "1",
    //         condition: "F00",
    //         com: "zhongtong",
    //         status: "200",
    //         state: "3",
    //         data: [
    //             {
    //                 statu: "已签收",
    //                 time: "2023-08-25 21:30:52",
    //                 ftime: "2023-08-25 21:30:52",
    //                 // tslint:disable-next-line:max-line-length
    //                 context: "【深圳市】 您的快递已签收，签收人在【深圳南山塘朗村191栋店】取件。如有疑问请联系业务员：18165703837，代理点电话：18165703837，投诉电话：0755-86114901。感谢使用中通快递，期待再次为您服务！"
    //             },
    //             {
    //                 statu: "运输中",
    //                 time: "2023-08-25 17:09:40",
    //                 ftime: "2023-08-25 17:09:40",
    //                 // tslint:disable-next-line:max-line-length
    //                 context: "【深圳市】 快件已在 快递超市 的【深圳南山塘朗村191栋店】暂放，【取件地址：塘朗老村中通快递点对面全家福便利店191-2号】，请及时取件。如有疑问请联系业务员：18165703837，代理点电话：18165703837，投诉电话：0755-86114901"
    //             },
    //             {
    //                 statu: "运输中",
    //                 time: "2023-08-25 13:54:25",
    //                 ftime: "2023-08-25 13:54:25",
    //                 // tslint:disable-next-line:max-line-length
    //                 context: "【深圳市】深圳桃源 的业务员【塘朗营业部吴清友,18165703837】正在为您派件（95720为中通快递员外呼专属号码，请放心接听，如有问题可联系网点:0755-36550506、0755-86114901,投诉电话:0755-86114901）"
    //             },
    //             {
    //                 statu: "运输中",
    //                 time: "2023-08-25 13:54:15",
    //                 ftime: "2023-08-25 13:54:15",
    //                 context: "【深圳市】 快件已到达 深圳桃源"
    //             },
    //             {

    //                 time: "2023-08-25 11:03:49",
    //                 ftime: "2023-08-25 11:03:49",
    //                 context: "【深圳市】 快件已发往 深圳桃源"
    //             },
    //             {

    //                 time: "2023-08-25 10:56:51",
    //                 ftime: "2023-08-25 10:56:51",
    //                 context: "【深圳市】 快件已到达 深圳中心"
    //             },
    //             {

    //                 time: "2023-08-24 16:44:25",
    //                 ftime: "2023-08-24 16:44:25",
    //                 context: "【金华市】 快件已发往 深圳中心"
    //             },
    //             {

    //                 time: "2023-08-24 16:41:36",
    //                 ftime: "2023-08-24 16:41:36",
    //                 context: "【金华市】 快件已到达 义乌中转部"
    //             },
    //             {

    //                 time: "2023-08-24 15:34:44",
    //                 ftime: "2023-08-24 15:34:44",
    //                 context: "【金华市】 快件已发往 深圳中心"
    //             },
    //             {

    //                 time: "2023-08-24 15:30:25",
    //                 ftime: "2023-08-24 15:30:25",
    //                 context: "【金华市】 义乌江南（0579-82405623）唐娅（1部扫描）（18266906991） 已揽收"
    //             }
    //         ]
    //     };
    // }

}

